#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "cache.h"
#include "ReadFile.h"

int main()
{	
	/********关于文件读取操作的变量***********/
	UINT8 OpenFileName[256]={0};
	FILE *fp=NULL;
	UINT8 FileBuffer[MAX_RECORD_LEN]={0};
	int L;
	int iRetVal;
	/*******trace variable***************/
	double time;
	int count=0;
	int devno,blkno,bcount,Opera_flag,secno,scount;
	/*****compute delay****/
	double delay=0.0;
	double cur_delay;
	/*******初始化数组arr（cache）************/
	init_arr();
	/**********初始化opagemap***************************/
	//一块包含64个页（128k） 2g=8192*128k
	opm_init(8192);
	printf("input trace file\n");
	fgets(OpenFileName,256,stdin);
	L=strlen(OpenFileName);
	/************处理掉输入的换行符*******************/
	if(L>0)
	{
		if(OpenFileName[L-1]=='\n'|| OpenFileName[L-1]=='\t')
		{
			OpenFileName[L-1]='\0';
		}
		L--;
	}
	//打开文件
	fp=fopen(OpenFileName,"r");
	if(fp==NULL)
	{
		printf("Open file %s is failed !\n",OpenFileName);
		exit(0);
	}else{
		printf("open file %s is successed !\n",OpenFileName);
	}
	//test point;
	
	while(1)
	{
		memset(FileBuffer,0x00,sizeof(FileBuffer));
		iRetVal=ReadRecordFromFile(fp,FileBuffer);
		if(iRetVal==-1){
			printf(" Exec ReadRecordFromFile failed,please check!\n");
			break;
		}else if(iRetVal==1)
		{
			printf("the file %s read finished!\n",OpenFileName);
			break;
		}else{
			if(sscanf(FileBuffer,"%lf %d %d %d %d\n",&time,&devno,&secno,&scount,&Opera_flag)==0)
			{
				printf("Wrong number of arguments for I/O trace event type\n");
				printf("Filebuffer is %s",FileBuffer);
				break;
			}
			// the test sentence
			//printf("the secno is %d\t the scount is %d\n",secno,scount);
			// invoke cacheManage function
			//test point
			cur_delay=cacheManage(secno,scount,Opera_flag);
			//test point
			count++;
			printf("the request secno (%d),size(%d),flag(%d),cost time(%f)\n",secno,scount,Opera_flag,cur_delay);
			delay+=cur_delay;

		}
	}
	//print result;
	printf("take all time is %f\n", delay);


	return 0;
}